package com.atguigu.tingshu.account.receiver;

import com.atguigu.tingshu.account.service.UserAccountService;
import com.atguigu.tingshu.common.constant.KafkaConstant;
import lombok.extern.slf4j.Slf4j;
import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.annotation.KafkaListener;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

/**
 * @author atguigu-mqx
 * @ClassName AccountReceiver
 * @description: TODO
 * @date 2023年10月27日
 * @version: 1.0
 */
@Component
@Slf4j
public class AccountReceiver {

    @Autowired
    private UserAccountService userAccountService;

    /**
     * 监听消息初始化账户信息。
     * @param record
     */
    @KafkaListener(topics = KafkaConstant.QUEUE_USER_REGISTER)
    public void userRegister(ConsumerRecord<String,Object> record){
        //  获取用户Id
        Long userId = Long.parseLong(record.value().toString());
        try {
            //  判断
            if (!StringUtils.isEmpty(userId)){
                //  初始化账户信息.
                userAccountService.addUserAccount(userId);
            }
        } catch (NumberFormatException e) {
            log.error("初始化账户失败{}",userId);
            //  消息记录表：将这个消息插入表中. userId = 24; undo_log
            throw new RuntimeException(e);
        }

    }

    /**
     * 扣减金额
     */
    @KafkaListener(topics = KafkaConstant.QUEUE_ACCOUNT_MINUS)
    public void minus(ConsumerRecord<String,Object> record){
        //  获取数据
        String orderNo = (String) record.value();
        //  判断
        if (!StringUtils.isEmpty(orderNo)){
            //  调用服务层方法.
            userAccountService.minus(orderNo);
        }
    }

    /**
     * 解锁金额
     */
    @KafkaListener(topics = KafkaConstant.QUEUE_ACCOUNT_UNLOCK)
    public void unlock(ConsumerRecord<String,Object> record){
        //  获取数据
        String orderNo = (String) record.value();
        //  判断
        if (!StringUtils.isEmpty(orderNo)){
            //  调用服务层方法.
            userAccountService.unlock(orderNo);
        }
    }


    /**
     * 监听账户充值消息.
     */
    @KafkaListener(topics = KafkaConstant.QUEUE_RECHARGE_PAY_SUCCESS)
    public void paySuccess(ConsumerRecord<String,Object> record){
        //  获取数据
        String orderNo = (String) record.value();
        //  判断
        if (!StringUtils.isEmpty(orderNo)){
            //  调用服务层方法.
            userAccountService.rechargePaySuccess(orderNo);
        }
    }

}
